// JS 逻辑
Page({
    data: {
        colors: ['#000000', '#ff0000', '#00ff00', '#0000ff', '#ffff00'],
        selectedColor: '#000000',
        brushSize: 4,
        signatureImage: '',
        points: [],
        allPoints: [] // 用于撤销功能
    },

    onLoad: function() {
        this.initCanvas();
    },

    initCanvas: function() {
        const { windowWidth, windowHeight } = wx.getSystemInfoSync();
        this.ctx = wx.createCanvasContext('signCanvas', this);
        this.canvasWidth = windowWidth * 0.9;
        this.canvasHeight = 300;

        this.setData({
            canvasWidth: this.canvasWidth,
            canvasHeight: this.canvasHeight
        });

        // 绘制初始空白画布
        this.drawCanvas();
    },

    selectColor: function(e) {
        const color = e.currentTarget.dataset.color;
        this.setData({ selectedColor: color });
    },

    brushSizeChange: function(e) {
        this.setData({ brushSize: e.detail.value });
    },

    onTouchStart: function(e) {
        const { x, y } = e.touches[0];
        this.startX = x;
        this.startY = y;

        // 保存当前状态用于撤销
        this.data.allPoints.push([...this.data.points]);

        this.data.points.push({
            x: x,
            y: y,
            color: this.data.selectedColor,
            size: this.data.brushSize
        });
    },

    onTouchMove: function(e) {
        const { x, y } = e.touches[0];
        this.data.points.push({
            x: x,
            y: y,
            color: this.data.selectedColor,
            size: this.data.brushSize
        });

        this.drawCanvas();
    },

    onTouchEnd: function() {
        this.drawCanvas();
    },

    drawCanvas: function() {
        this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
        this.ctx.setFillStyle('#ffffff');
        this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

        // 绘制网格背景
        this.ctx.setStrokeStyle('#f0f0f0');
        this.ctx.setLineWidth(1);

        for (let i = 0; i < this.canvasWidth; i += 15) {
            this.ctx.beginPath();
            this.ctx.moveTo(i, 0);
            this.ctx.lineTo(i, this.canvasHeight);
            this.ctx.stroke();
        }

        for (let i = 0; i < this.canvasHeight; i += 15) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, i);
            this.ctx.lineTo(this.canvasWidth, i);
            this.ctx.stroke();
        }

        // 绘制签名
        if (this.data.points.length > 0) {
            this.ctx.setLineCap('round');
            this.ctx.setLineJoin('round');

            let currentColor = this.data.points[0].color;
            let currentSize = this.data.points[0].size;

            this.ctx.beginPath();
            this.ctx.setStrokeStyle(currentColor);
            this.ctx.setLineWidth(currentSize);
            this.ctx.moveTo(this.data.points[0].x, this.data.points[0].y);

            for (let i = 1; i < this.data.points.length; i++) {
                if (this.data.points[i].color !== currentColor || this.data.points[i].size !== currentSize) {
                    this.ctx.stroke();
                    this.ctx.beginPath();
                    currentColor = this.data.points[i].color;
                    currentSize = this.data.points[i].size;
                    this.ctx.setStrokeStyle(currentColor);
                    this.ctx.setLineWidth(currentSize);
                    this.ctx.moveTo(this.data.points[i-1].x, this.data.points[i-1].y);
                }
                    this.ctx.lineTo(this.data.points[i].x, this.data.points[i].y);
            }

            this.ctx.stroke();
        }

        this.ctx.draw();
    },

    undo: function() {
        if (this.data.allPoints.length > 0) {
            this.data.points = this.data.allPoints.pop();
            this.drawCanvas();
        }
    },

    clearCanvas: function() {
        this.data.points = [];
        this.data.allPoints = [];
        this.drawCanvas();
    },

    saveSignature: function() {
        const that = this;
        wx.canvasToTempFilePath({
            canvasId: 'signCanvas',
            success: function(res) {
                that.setData({
                    signatureImage: res.tempFilePath
                });

                wx.showToast({
                    title: '签名已保存',
                    icon: 'success'
                });
            },
            fail: function(err) {
                console.error(err);
                wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                });
            }
        }, this);
    },

    downloadImage: function() {
        const that = this;
        wx.saveImageToPhotosAlbum({
            filePath: this.data.signatureImage,
            success: function() {
                wx.showToast({
                    title: '图片已保存到相册',
                    icon: 'success'
                });
            },
            fail: function(err) {
                console.error(err);
                wx.showToast({
                    title: '保存失败，请检查权限设置',
                    icon: 'none'
                });
            }
        });
    }
});